const Router = require('koa-router');
const sanitizeHtml = require('sanitize-html');
const crypto = require('crypto');
const moment = require('moment');

const query = require('../lib/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const router = new Router();

router.prefix('/open');

module.exports = router;

/**
 * 根据openId获取课程信息
 */
router.get('/lesson/:openId', async (ctx, next) => {
  let { openId } = ctx.params;
  if (!openId || openId.length !== 32) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }
  let list = await query(`select * from lesson where openId="${openId}"`);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  const { name, type, avatar, content, create_time } = list[0];

  const timestamp = new Date(create_time);

  // 二维码有效期 试听-6天  报名-1年
  if (+type === 1 && (Date.now() - timestamp.getTime() > 518400000) || +type === 2 && (Date.now() - timestamp.getTime() > 31536000000)) {
    ctx.body = await wrapper({
      error: '二维码已经过期',
    });
    return false;
  }

  ctx.body = await wrapper({
    name,
    avatar,
    content: JSON.parse(unescape(content)),
  });
});
